#######################################################################
# Copyright (c) 2025 Huawei Technologies Co., Ltd.
# Openfuyao is licensed under Mulan PSL v2.
# You can use this software according to the terms and conditions of the Mulan PSL v2.
# You may obtain a copy of Mulan PSL v2 at:
#     http://license.coscl.org.cn/MulanPSL2
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
# PURPOSE.
# See the Mulan PSL v2 for more details.
#######################################################################

#!/bin/bash

# 脚本路径定义
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PREREQ_DIR="${SCRIPT_DIR}/../prerequirement"
REDIS_DIR="${SCRIPT_DIR}/../redis"
CPU_TEST_BINARY="${SCRIPT_DIR}/../cputest.arm"

# 全局配置
OPEN_PRE_SCRIPT="numa-distance-open-pre.sh"
CLOSE_PRE_SCRIPT="numa-distance-close-pre.sh"
OPEN_CPU_RANGE="0-94:50,99-127:50"
CLOSE_CPU_RANGE="0-62:50,67-127:50"

# 默认参数
TEST_TYPE="open"

# 帮助信息
show_help() {
    echo "用法: $0 [选项]"
    echo "选项:"
    echo "  -t <类型>      测试类型 (open/close, 默认: open)"
    echo "  -h             显示此帮助信息"
    exit 0
}

# 错误处理函数
handle_error() {
    echo "错误: $1 执行失败" >&2
    
    # 执行清理脚本
    echo "==== 开始清理临时任务 ===="
    bash "${PREREQ_DIR}/delete-temp-task.sh" || {
        echo "警告: 清理脚本执行失败，但继续退出" >&2
    }
    
    exit 1
}

# 清理函数，用于trap捕获信号
cleanup() {
    echo "==== 检测到中断，开始清理 ===="
    bash "${PREREQ_DIR}/delete-temp-task.sh" || {
        echo "警告: 清理脚本执行失败" >&2
    }
    exit 1
}

# 注册信号处理
trap cleanup SIGINT SIGTERM

# 解析命令行参数
while [[ $# -gt 0 ]]; do
    case $1 in
        -t)
            TEST_TYPE="$2"
            shift 2
            ;;
        -h)
            show_help
            ;;
        *)
            echo "未知参数: $1" >&2
            show_help
            ;;
    esac
done

# 验证参数
if [[ "$TEST_TYPE" != "open" && "$TEST_TYPE" != "close" ]]; then
    echo "错误: 测试类型必须是open或close" >&2
    show_help
fi

# 根据类型设置参数
if [[ "$TEST_TYPE" == "open" ]]; then
    PRE_SCRIPT="$OPEN_PRE_SCRIPT"
    CPU_STRESS_RANGE="$OPEN_CPU_RANGE"
else
    PRE_SCRIPT="$CLOSE_PRE_SCRIPT"
    CPU_STRESS_RANGE="$CLOSE_CPU_RANGE"
fi

# 步骤1: 执行前置部署脚本
echo "==== 执行前置部署脚本 ===="
bash "${PREREQ_DIR}/${PRE_SCRIPT}" || handle_error "前置部署脚本"

# 步骤2: 执行Redis自动化脚本
echo "==== 执行Redis自动化脚本 ===="
python3 "${REDIS_DIR}/auto_redis.py" -n 3 -r 10000000 -t ${TEST_TYPE} -stressCommand "${CPU_TEST_BINARY} 0 ${CPU_STRESS_RANGE}" || handle_error "Redis自动化脚本"

# 步骤3: 清理临时任务
echo "==== 清理临时任务 ===="
bash "${PREREQ_DIR}/delete-temp-task.sh" || handle_error "清理脚本"

echo "==== 所有步骤执行完成 ===="
exit 0